let publicKey = "";
let account_Server = "/accountSer"

let Authorization = "";
let refreshToken = "";

let phone_is_exist = false;
let email_is_exist = false;

let code = "";
// 加载页面时读取配置信息
window.onload = function () {
    $.ajaxSettings.async = false;
    $.getJSON("/js/properties.json", function (data) {
        account_Server = data.accountServer;
    });
    $.ajax({
        url: "/js/publicKey.txt",
        success: function(data) {
            publicKey = data;
        }
    });
    // 获取令牌
    Authorization = getCookie("Authorization")
    refreshToken = getCookie("refreshToken")
}

function login(){
    let password = $("#password").val();
    let username = $("#username").val();
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(publicKey)  // 此处设置公钥
    let encodedPassword = encrypt.encrypt(password)  // 这里对密码进行加密

    $.ajax({
        type: "POST",
        async: false,
        url: account_Server + "/account/LOrR/loginWithPassword",
        data: {
            userName: username,
            encodedPassword: encodedPassword
        },
        success: function (data) {
            if (data.resp_code === 0){
                // 返回码为 0 表示成功
                setAuthCookie(data, 1);
                // 获取令牌
                Authorization = getCookie("Authorization")
                refreshToken = getCookie("refreshToken")
                refreshAuth(Authorization, refreshToken, "");
                // 跳转首页
                toHomePage("l");
            }else {
                // 其余为失败
                setAuthCookie(data, -1);
                cocoMessage.error(2000, data.resp_msg);
            }
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText, function () {
                console.log(err);
            });
        }
    });
}

var phoneReg = /(^1[3|4|5|7|8]\d{9}$)|(^09\d{8}$)/;//手机号正则
var emailReg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;//邮箱正则
var count = 60; //间隔函数，1秒执行
var InterValObj; //timer变量，控制时间
var curCount;//当前剩余秒数

function phoneIsExist(){
    let phone = $.trim($('#register-phone').val());
    if (phone === null || phone === ""){
        return false;
    }
    $.ajax({
        type: "GET",
        async: false,
        url: account_Server+"/account/LOrR/phoneIsExist",
        data: {
            phone: phone,
        },
        success: function (data) {
            if (data.resp_code === 0) {
                // 成功
                cocoMessage.info(2000, data.resp_msg);
                $("#error-register-phone").html("");
                phone_is_exist = false;
            } else {
                // 失败
                cocoMessage.error(2000, data.resp_msg);
                $("#error-register-phone").html(data.resp_msg);
                phone_is_exist = true;
            }
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText);
        }
    });
}
function emailIsExist(){
    let email = $.trim($('#register-email').val());
    if (email === null || email === ""){
        return false;
    }
    $.ajax({
        type: "GET",
        async: false,
        url: account_Server+"/account/LOrR/emailIsExist",
        data: {
            email: email,
        },
        success: function (data) {
            if (data.resp_code === 0) {
                // 成功
                cocoMessage.info(2000, data.resp_msg);
                $("#error-register-email").html("");
                email_is_exist = false;
            } else {
                // 失败
                cocoMessage.error(2000, data.resp_msg);
                $("#error-register-email").html(data.resp_msg);
                email_is_exist = true;
            }
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText);
        }
    });
}

let $btnSendCode = $(".btnSendCode");
function sendMessage(type) {
    curCount = count;
    if (type !== "loginByCode"){
        let phone = $.trim($('#'+type+'-phone').val());
        let $errorPhone = $("#error-"+type+"-phone");
        if (!phoneReg.test(phone)) {
            $errorPhone.html("请输入合法手机号");
            return false;
        }
        $errorPhone.html("");
    }

    let email = $.trim($('#'+type+'-email').val());
    let $errorEmail = $("#error-"+type+"-email");
    if (!emailReg.test(email)) {
        $errorEmail.html("请输入合法邮箱号");
        return false;
    }
    $errorEmail.html("");

    sendCode(email);
    //设置button效果，开始计时
    $btnSendCode.attr("disabled", "true");
    $btnSendCode.html( + curCount + "秒再获取");
    InterValObj = window.setInterval(SetRemainTime, 1000); //启动计时器，1秒执行一次
    //向后台发送处理数据
    return false;
}
function SetRemainTime() {
    if (curCount === 0) {
        window.clearInterval(InterValObj);//停止计时器
        $btnSendCode.removeAttr("disabled");//启用按钮
        $btnSendCode.html("重新发送");
    }
    else {
        curCount--;
        $btnSendCode.html( + curCount + "秒再获取");
    }
}

function sendCode(phoneNumber){
    $.ajax({
        type: "GET",
        async: false,
        url: account_Server+"/account/LOrR/sendCode",
        data: {
            phoneNumber: phoneNumber,
        },
        success: function (data) {
            if (data.resp_code === 0) {
                // 成功
                cocoMessage.info(2000, data.resp_msg);
                let date = new Date();
                date.setTime( date.getTime() + (60*2000));
                let expires = "expires="+date.toUTCString();
                document.cookie = "code="+data.datas+";expires="+expires+";path=/";
                // console.log(getCookie("code"));
            } else {
                // 失败
                cocoMessage.error(2000, data.resp_msg);
                window.clearInterval(InterValObj);//停止计时器
                $btnSendCode.removeAttr("disabled");//启用按钮
                $btnSendCode.html("发送验证码");
            }
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText);
            window.clearInterval(InterValObj);//停止计时器
            $btnSendCode.removeAttr("disabled");//启用按钮
            $btnSendCode.html("发送验证码");
        }
    });
}

function registerSubmit(){
    let name = $("#register-name").val();
    let phone = $("#register-phone").val();
    let email = $("#register-email").val();
    let password = $("#register-password").val();
    let conPassword = $("#register-conPassword").val();
    let inputCode = $("#register-code").val().toUpperCase();
    let role = $('input[name="login-for"]:checked').val();
    let terms = $("#register-terms-conditions").is(":checked");

    let code = getCookie("code");

    if (name === "" || name === null){
        $("#error-register-name").html("不能为空");
        return false;
    }else {
        $("#error-register-name").html("");
    }
    if (phone === "" || phone === null){
        $("#error-register-phone").html("不能为空");
        return false;
    }else if (phone_is_exist){
        $("#error-register-phone").html("该手机号已存在");
        return false;
    }else {
        $("#error-register-phone").html("");
    }
    if (email === "" || email === null){
        $("#error-register-email").html("不能为空");
        return false;
    }else if (email_is_exist){
        $("#error-register-email").html("该邮箱已存在");
        return false;
    }else if (!emailReg.test(email)){
        $("#error-register-email").html("邮箱格式不正确");
        return false;
    }else {
        $("#error-register-email").html("");
    }
    if (password === "" || password === null){
        $("#error-register-password").html("不能为空");
        return false;
    }else {
        $("#error-register-password").html("");
    }
    if (conPassword === "" || conPassword === null){
        $("#error-register-conPassword").html("不能为空");
        return false;
    }else if (conPassword !== password){
        $("#error-register-conPassword").html("两次密码输入不一致");
        return false;
    }else {
        $("#error-register-conPassword").html("");
    }
    if (inputCode === "" || inputCode === null){
        $("#error-register-code").html("不能为空");
        return false;
    }else if (code === "" || code === null){
        $("#error-register-code").html("验证码已过期");
        return false;
    }else if (inputCode !== code){
        $("#error-register-code").html("验证码输入错误");
        return false;
    }else {
        $("#error-register-code").html("");
    }
    if (role === "job_seeker" || role === "company"){
        $("#error-register-role").html("");
    }else {
        $("#error-register-role").html("不能为空");
        return false;
    }
    if (terms === false){
        $("#register-agree").html("请同意协议");
        return false;
    }else {
        $("#register-agree").html("");
    }


    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(publicKey)  // 此处设置公钥
    let encodedPassword = encrypt.encrypt(password)  // 这里对密码进行加密

    // console.log("name = "+name+
    //             "phone = "+phone+
    //             "email = "+email+
    //             "password = "+ password+
    //             "conPassword = "+conPassword+
    //             "encodedPassword = "+encodedPassword+
    //             "code = "+inputCode+
    //             "role = "+role+
    //             "terms = "+terms);
    $.ajax({
        type: "POST",
        async: false,
        url: account_Server+"/account/LOrR/registerAccount",
        headers: {
            "Content-Type": "application/json",
        },
        data: JSON.stringify({
            "userName": name,
            "phone": phone,
            "email": email,
            "password": encodedPassword,
            "role": role,
        }),
        success: function (data) {
            if (data.resp_code === 0) {
                // 成功
                cocoMessage.info(2500, data.resp_msg);
            } else {
                // 失败
                cocoMessage.error(2500, data.resp_msg);
            }
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText);
        }
    });

}

function loginByCode(){
    let email = $.trim($('#loginByCode-email').val());
    let code = $.trim($('#loginByCode-code').val().toUpperCase());

    if (email === "" || email === null){
        $("#error-loginByCode-email").html("不能为空");
        return false;
    }else {
        $("#error-loginByCode-email").html("");
    }
    if (code === "" || code === null){
        $("#error-loginByCode-code").html("不能为空");
        return false;
    }else {
        $("#error-loginByCode-code").html("");
    }

    $.ajax({
        type: "POST",
        async: false,
        url: account_Server + "/account/LOrR/loginWithCode",
        data: {
            userName: email,
            code: code
        },
        success: function (data) {
            if (data.resp_code === 0){
                // 返回码为 0 表示成功
                setAuthCookie(data, 1);
                // 获取令牌
                Authorization = getCookie("Authorization")
                refreshToken = getCookie("refreshToken")
                refreshAuth(Authorization, refreshToken, "");
                // 跳转首页
                toHomePage("l");
            }else {
                // 其余为失败
                setAuthCookie(data, -1);
                cocoMessage.error(2000, data.resp_msg);

                if (data.resp_code === -1){
                    $("#error-loginByCode-email").html(data.resp_msg);
                }else if (data.resp_code === 1){
                    $("#error-loginByCode-code").html(data.resp_msg);
                }
            }
        },
        error: function (err) {
            // 异常
            cocoMessage.error(2000, err.statusText, function () {
                console.log(err);
            });
        }
    });
}
